import axios from "axios";
import { cloneDeep } from "lodash";
import { clearDeep } from "@/common/util";
import qs from "qs";

const instance = axios.create({
  baseURL: "http://47.99.135.191:8080/",
  withCredentials: true,
  paramsSerializer: params => {
    return qs.stringify(params, { arrayFormat: "repeat" });
  }
});

instance.interceptors.request.use(config => {
  if (!config.headers["Authorization"]) {
    const accessToken = localStorage.getItem("token");

    if (accessToken) {
      config.headers = config.headers || {};
      config.headers["Authorization"] = `Bearer ${accessToken}`;
    }
  }
  config.params = config.params || {};
  // prevent browser side cache
  config.params.ts = new Date().getTime();

  if (config.data && !(config.data instanceof FormData)) {
    // clone data
    config.data = cloneDeep(config.data);
    clearDeep(config.data); // 数据清洗
  }

  config.headers["Accept-Language"] = "zh-CN";

  return config;
});

export default instance;
